package com.safeneeds.sysmana.entity.dao.impl;

import com.safeneeds.sysmana.dto.DataStoreLog;
import com.safeneeds.sysmana.entity.SysLog;
import com.safeneeds.sysmana.entity.dao.ISysLogDao;
import com.safeneeds.util.base.BaseHibernateDao;
import com.safeneeds.util.date.DateUtil;
import com.safeneeds.util.other.StringUtil;
import com.safeneeds.util.page.PageInfo;

/**
 * 日志管理Dao
 * @author gaof
 * @date 2016年12月21日
 */
public class SysLogDao extends BaseHibernateDao<SysLog, Long> implements ISysLogDao {

	/**
	 * 获取日志分页数据
	 * @param pageInfo
	 * @return
	 */
	@Override
	public PageInfo listLogPage(PageInfo pageInfo, DataStoreLog dataStore) {
		
		String hsql = "FROM SysLog";
		String countSql = "SELECT COUNT(*) FROM SysLog";
		String whereSql = "";
		String orderSql = " order by logTime desc";
		
		if(dataStore != null){
			
			whereSql += " where 1=1";
			
			//用户名检索
			if(!StringUtil.isEmpty(dataStore.getName())){
				whereSql += " and userNameHis like '%" + StringUtil.addQuote(dataStore.getName()) + "%'";
			}
			
			//登录ip检索
			if(!StringUtil.isEmpty(dataStore.getIp())){
				whereSql += " and logIp = '" + StringUtil.addQuote(dataStore.getIp()) + "'";
			}
			
			//日志类型检索
			if(!StringUtil.isEmpty(dataStore.getType())){
				whereSql +=  " and type = '" + StringUtil.addQuote(dataStore.getType()) + "'";
			}
			
			//操作时间检索
			if(!StringUtil.isEmpty(dataStore.getStart()) && !StringUtil.isEmpty(dataStore.getEnd())){//有开始时间和结束时间
				if(DateUtil.compareDateYYYYMMDD(dataStore.getStart(), dataStore.getEnd())){//开始时间大于结束时间
					whereSql += " and logTime >= to_timestamp('" + dataStore.getEnd() + " 00:00:00', 'yyyy-MM-dd HH24:MI:SS')"
							 + " and logTime <= to_timestamp('" + dataStore.getStart() + " 23:59:59', 'yyyy-MM-dd HH24:MI:SS')";
				}else{
					whereSql += " and logTime <= to_timestamp('" + dataStore.getEnd() + " 23:59:59', 'yyyy-MM-dd HH24:MI:SS')"
							 + " and logTime >= to_timestamp('" + dataStore.getStart() + " 00:00:00', 'yyyy-MM-dd HH24:MI:SS')";
				}
			}else if(!StringUtil.isEmpty(dataStore.getStart())){//只有开始时间
				whereSql += " and logTime >= to_timestamp('" + dataStore.getStart() + " 00:00:00', 'yyyy-MM-dd HH24:MI:SS')";
			}else if(!StringUtil.isEmpty(dataStore.getEnd())){//只有结束时间
				whereSql += " and logTime <= to_timestamp('" + dataStore.getEnd() + " 23:59:59', 'yyyy-MM-dd HH24:MI:SS')";
			}
		}
		
		pageInfo.setTotalCountHbSQL(countSql + whereSql);
		pageInfo.setListHbSql(hsql + whereSql + orderSql);
		
		return pageInfo;
	}

	/**
	 * 添加系统日志
	 * @param log
	 */
	@Override
	public void addLog(SysLog log) {
		this.saveEntity(log);
	}

}
